package com.wanlian.netty.msg;

import java.nio.charset.Charset;

import com.wanlian.json.JsonStringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 编码器
 *
 * @author ailianlu2
 */
public class PeerMsgEncoder extends MessageToByteEncoder<PeerMsg> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, PeerMsg peerMsg, ByteBuf byteBuf)
            throws Exception {
        int length = peerMsg.getHead().getLength();
        int version = peerMsg.getHead().getVersion();
        byteBuf.writeInt(peerMsg.getHead().getHead_data());
        byteBuf.writeInt(version);
        byteBuf.writeInt(peerMsg.getHead().getMsgType());
        byteBuf.writeInt(length);
        BaseMsg baseMsg = peerMsg.getBaseMsg();
        String data = JsonStringUtil.writeValueAsString(baseMsg);
        byteBuf.writeBytes(data.getBytes(Charset.forName("UTF-8")));
    }

}
